package com.cdk8s.example.simplespringboot.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 文件操作工具类.
 */
@Slf4j
public final class DownloadUtil {

	/**
	 * 通过网络 url 获取文件流（必须包含 http 或 https 开头）
	 */
	public static InputStream getInputStreamByFileHttpUrl(String fileHttpUrl) {

		InputStream inputStream = null;
		try {
			String strUrl = fileHttpUrl.trim();
			URL url = new URL(strUrl);

			//允许所有证书 start
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
			//允许所有证书 end

			//打开请求连接
			URLConnection connection = url.openConnection();
			HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
			httpURLConnection.setReadTimeout(5000);
			httpURLConnection.setConnectTimeout(5000);
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setRequestProperty("User-Agent", UserAgentUtil.getRandomUserAgent());
			httpURLConnection.connect();
			int responseCode = httpURLConnection.getResponseCode();
			if (responseCode > 300 && responseCode < 400) {
				// 301，302，303，307，308 表示重定向需要再请求一次
				// 获取重定向地址
				String location = httpURLConnection.getHeaderField("Location");
				url = new URL(location);
				httpURLConnection = (HttpURLConnection) url.openConnection();
				httpURLConnection.setReadTimeout(5000);
				httpURLConnection.setConnectTimeout(5000);
				httpURLConnection.setRequestMethod("GET");
				httpURLConnection.setRequestProperty("User-Agent", UserAgentUtil.getRandomUserAgent());
				httpURLConnection.connect();
			}
			// 取得输入流，并使用Reader读取
			inputStream = httpURLConnection.getInputStream();
			return inputStream;
		} catch (Exception e) {
			log.error("------zch------获取网络文件出现异常，URL：<{}>", fileHttpUrl);
			ExceptionUtil.printStackTraceAsString(e);
		}
		return inputStream;
	}

	/**
	 * 通过网络 url 获取图片流（必须包含 http 或 https 开头）
	 */
	@SneakyThrows
	public static byte[] getByteByFileHttpUrl(final String fileHttpUrl) {
		InputStream inputStreamByFileHttpUrl = getInputStreamByFileHttpUrl(fileHttpUrl);
		if (null != inputStreamByFileHttpUrl) {
			return inputStreamToByteArray(inputStreamByFileHttpUrl);
		}
		return null;
	}


	public static byte[] inputStreamToByteArray(final InputStream inputStream) throws IOException {
		// return ByteStreams.toByteArray(inputStream);// guava 方案
		return IOUtils.toByteArray(inputStream);// commons-io 方案
	}


	// =================================================================================
	// 信任所有证书
	private static class MyTrustManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}

	private static class MyHostnameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}
	// =================================================================================

}
